//
//  ZallTextField.m
//  ZJS
//
//  Created by zxx on 2017/1/5.
//  Copyright © 2017年 zall. All rights reserved.
//

#import "ZallTextField.h"

@interface ZallTextField()

@property(strong, nonatomic) UIView *cleanView;
@property(strong, nonatomic) UIButton *cleanButton;

@end

@implementation ZallTextField

#pragma mark - init
- (instancetype)init{
    return self = [self initWithFrame:CGRectZero];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.rightView = self.cleanView;
        self.rightViewMode = UITextFieldViewModeAlways;
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    if (self.rightViewMargin) {
        self.cleanView.frame = CGRectMake(CGRectGetWidth(self.frame) - 20 - self.rightViewMargin, 0, 20 + self.rightViewMargin, CGRectGetHeight(self.frame));
    }else {
        self.cleanView.frame = CGRectMake(CGRectGetWidth(self.frame) - 20, 0, 20, 20);
    }
    self.cleanButton.frame = CGRectMake(0, 0, 20, 20);
    self.cleanButton.centerY = CGRectGetHeight(self.frame)/2.0;
    
    for (UIScrollView *view in self.subviews) {
        if ([view isKindOfClass:[UIScrollView class]]) {
            CGPoint offset = view.contentOffset;
            if (offset.y != 0) {
                offset.y = 0;
                view.contentOffset = offset;
            }
            break;
        }
    }
    
}

#pragma mark - clean 按钮事件
- (void)cleanClick:(UIButton *)sender{
    self.text = @"";
}

#pragma mark - getter
- (UIView *)cleanView{
    if (!_cleanView) {
        _cleanView = [[UIView alloc] init];
        _cleanView.backgroundColor = [UIColor clearColor];
        [_cleanView addSubview:self.cleanButton];
        
    }
    return _cleanView;
}

- (UIButton *)cleanButton{
    if (!_cleanButton) {
        _cleanButton = [[UIButton alloc] init];
        [_cleanButton setImage:[UIImage imageNamed:@"textfield_clean"] forState:UIControlStateNormal];
        [_cleanButton addTarget:self action:@selector(cleanClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cleanButton;
}

#pragma mark - setter
/**
 *  @brief  设置内左边距
 */
- (void)setLeftViewMargin:(CGFloat)leftViewMargin{
    _leftViewMargin = leftViewMargin;
    CGRect frame = [self frame];
    frame.size.width = _leftViewMargin;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    self.leftViewMode = UITextFieldViewModeAlways;
    self.leftView = leftview;
}

/**
 *  @brief  设置删除按钮右边距
 */
- (void)setRightViewMargin:(CGFloat)rightViewMargin{
    _rightViewMargin = rightViewMargin;
    [self setNeedsLayout];
}


@end
